import docSetting from './setting/doc-setting'
import DocLayout from './layout/doc-layout.vue'
import Vue from 'vue'

export { docSetting, DocLayout }

export default function createAbpxDoc(router, options) {
  const setting = Object.assign(docSetting, options)
  if (!setting.menus || setting.menus.length === 0) return
  if (setting.package.repository && setting.package.repository.type) {
    setting.package.repository.url = setting.package.repository.url.substring(
      setting.package.repository.type.length + 1
    )
  }
  Vue.prototype.$docSetting = setting
  const children = []
  let defaultPath = ''
  const routePrefix = trim(setting.routePrefix, '/')

  setting.menus.forEach(item => {
    if (item.children) {
      item.children.forEach(subItem => {
        if (routePrefix) {
          subItem.path = `/${routePrefix}/${trim(subItem.path, '/')}`
        }
        if (subItem.path && subItem.component) {
          children.push({
            path: subItem.path,
            component: subItem.component,
            meta: {
              title: subItem.title
            }
          })
          if (item.default) {
            defaultPath = item.path
          }
        } else {
          console.error('%s,请检查属性[path]与[component]是否正确', JSON.stringify(subItem))
        }
      })
    }
  })

  if (children.length === 0) return
  if (!defaultPath) {
    defaultPath = children[0].path
  }

  router.addRoutes([
    {
      path: '/zh-CN',
      component: DocLayout,
      redirect: defaultPath,
      children
    },
    {
      path: '',
      redirect: defaultPath
    },
    {
      path: '*',
      redirect: defaultPath
    }
  ])
}

function trimStart(str, value) {
  let index = 0
  for (index = 0; index < str.length; index++) {
    if (str.charAt(index) !== value) break
  }
  return str.slice(index, str.length)
}

function trimEnd(str, value) {
  let index = 0
  for (index = str.length - 1; index >= 0; index--) {
    if (str.charAt(index) !== value) break
  }
  return str.slice(0, index + 1)
}

function trim(str, value) {
  return trimStart(trimEnd(str, value), value)
}
